package com.heima.article;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleHtmlTask {

    //    生成指定文章的静态页面，放到minIO中
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinIOService minIOService;
    @Autowired
    @Lazy
    private IApArticleService apArticleService;
    @Async
    public void createHtml( ApArticle apArticle,String content){
        //        查询模板中需要的数据
        //        获取指定的模板
        try {
            Template template = configuration.getTemplate("article.ftl");

            List<Map> mapList = JSON.parseArray(content, Map.class);

            StringWriter writer = new StringWriter();
//        把模板和数据结合 放到一个writer流中
            Map dataModel = new HashMap();
            dataModel.put("content", mapList);
            template.process(dataModel, writer);  //Object dataModel, Writer out

//        把静态页面放到minIO中
            ByteArrayInputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            String url = minIOService.upload("article/" + apArticle.getId() + ".html", inputStream, "text/html");//String name, InputStream inputStream, String contentType

//        更新Aparticle中的静态页面url
            apArticle.setStaticUrl(url);
            apArticleService.updateById(apArticle);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
